package com.leigq.basaltools.util;

import org.junit.platform.commons.util.StringUtils;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.support.PropertiesLoaderUtils;

import java.io.IOException;
import java.util.Objects;
import java.util.Properties;

/**
 * Properties文件工具类
 * <br>
 * 参考:<a href='https://blog.csdn.net/qq_34845394/article/details/99654835'>Java 读取 Properties 文件</a>
 * <p>
 *
 * @author ：leigq <br>
 * </p>
 */
public abstract class PropertiesUtils {

    private static final ThreadLocal<Properties> PROPERTIES = new ThreadLocal<>();

    /**
     * 初始化 Properties
     *
     * @param path resources资源文件路径,如:/i18n/zh_CN.properties
     */
    public static void init(String path) {
        try {
            PROPERTIES.remove();
            PROPERTIES.set(PropertiesLoaderUtils.loadProperties(new ClassPathResource(path)));
        } catch (IOException e) {
            throw new RuntimeException(String.format("地址为 %s 的文件不存在", path), e);
        }
    }

    /**
     * 获取配置文件中的值
     *
     * @param key 键
     */
    public static String getValue(String key) {
        if (StringUtils.isBlank(key)) {
            throw new NullPointerException("key must be not null");
        }
        if (Objects.isNull(PROPERTIES.get())) {
            throw new NullPointerException("请先调用 init() 方法初始化 properties 文件");
        }
        key = key.trim();
        String property = PROPERTIES.get().getProperty(key);
        return StringUtils.isBlank(property) ? null : property.trim();
    }
}
